import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  // 基础路径地址在.env.development里面配置
  baseURL: process.env.VUE_APP_BASE_API,

  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    return Promise.reject('这是请求拦截器发生的错误' + error)
  }
)

// response interceptor
service.interceptors.response.use(
  // response表示请求返回回来的数据，在这个接口中，所有的数据默认包裹在data中
  response => {
    const { success, message, data } = response.data
    if (success) {
      return data
    } else {
      // 一切的错误都在响应拦截器拦截了，在每个方法中不用再次判断
      Message.error(message)
      // axios本质是封装的promise对象，错误时给它返回一个reject让promise对象状态改变为错误，并且结束promise对象
      return Promise.reject(new Error('请求的数据响应错误'))
    }
  },
  error => {
    Message.error('这是响应拦截器的报告--' + error.message)
    return Promise.reject(error)
  }
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
)

export default service
